// 接入讯飞聊天
// import { downloadPCM, downloadWAV } from "./js/download.js";
import CryptoJS from "crypto-js";
// import Enc from "enc";
// import TransWorker from "./js/transcode.worker.js";
// console.log(`output->TransWorker`, TransWorker);
// import VConsole from "vconsole";
// import { Base64 } from "js-base64";
// import { mount } from "sortablejs";
import VueMarkdown from 'vue-markdown'


// import marked from 'marked';
// cnpm  i  babel-runtime  -D

// "crypto-js": "^4.0.0",
// "enc": "^0.4.0",
// "vconsole": "^3.3.4",
// "js-base64": "^2.5.2"
//  yarn add vue-markdown --save
// cnpm i core-js -D
// let transWorker = new TransWorker();
// 地址必须填写，代表着大模型的版本号！！！！！！！！！！！！！！！！
let httpUrl = new URL("https://spark-api.xf-yun.com/v3.5/chat");
let modelDomain; // V1.1-V3.5动态获取，高于以上版本手动指定
//APPID，APISecret，APIKey在https://console.xfyun.cn/services/cbm这里获取
const APPID = "50ea2a56";
const API_SECRET = "YWQ5M2RlN2I0NjY2NmFlZTRlM2E3NWQ1";
const API_KEY = "bac0f3a53c74df98ff712c4dac28c776";

var total_res = "";

function getWebsocketUrl() {
  // console.log(httpUrl.pathname)
  // 动态获取domain信息
  switch (httpUrl.pathname) {
    case "/v1.1/chat":
      modelDomain = "general";
      break;
    case "/v2.1/chat":
      modelDomain = "generalv2";
      break;
    case "/v3.1/chat":
      modelDomain = "generalv3";
      break;
    case "/v3.5/chat":
      modelDomain = "generalv3.5";
      break;
  }

  return new Promise((resolve, reject) => {
    var apiKey = API_KEY;
    var apiSecret = API_SECRET;

    var url = "wss://" + httpUrl.host + httpUrl.pathname;

    // console.log("我打印的" + httpUrl.host)
    // console.log("我打印的" + httpUrl.pathname)

    var host = location.host;
    var date = new Date().toGMTString();
    var algorithm = "hmac-sha256";
    var headers = "host date request-line";
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrl.pathname} HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    resolve(url);
  });
}

export default {
  data() {
    return {
      bigModel: {},
      // 控制对话框的关闭
      ttsWS:{}
      
     
    };
  },
  mounted() {
    let that = this
    class TTSRecorder {
      constructor({ appId = APPID } = {}) {
        this.appId = appId;
        this.status = "init";
      }

      // 修改状态
      setStatus(status) {
        this.onWillStatusChange && this.onWillStatusChange(this.status, status);
        this.status = status;
      }

      // 连接websocket  inpMessage 文本框的值
      connectWebSocket(inpMessage) {
        this.setStatus("ttsing");
        return getWebsocketUrl().then((url) => {
          let ttsWS;
          if ("WebSocket" in window) {
            ttsWS = new WebSocket(url);
          } else if ("MozWebSocket" in window) {
            ttsWS = new MozWebSocket(url);
          } else {
            alert("浏览器不支持WebSocket");
            return;
          }
          this.ttsWS = ttsWS;
          that.ttsWS = ttsWS;
          ttsWS.onopen = (e) => {
            // 文本框的值
            this.webSocketSend(inpMessage);
          };
          ttsWS.onmessage = (e) => {
            // console.log(e.data,'==onmessage==')
            this.result(e.data);
          };
          ttsWS.onerror = (e) => {
            clearTimeout(this.playTimeout);
            this.setStatus("error");
            alert("WebSocket报错，请f12查看详情");
            console.error(
              `详情查看：${encodeURI(url.replace("wss:", "https:"))}`
            );
          };
          ttsWS.onclose = (e) => {
            console.log(e);
          };
        });
      }

      // websocket发送数据
      webSocketSend(inpMessage) {
        console.log( that.text,' that.text');
        var params = {
          header: {
            app_id: this.appId,
            uid: "fd3f47e4-d",
          },
          parameter: {
            chat: {
              domain: modelDomain,
              temperature: 0.5,
              max_tokens: 1024,
            },
          },
          payload: {
            message: {
              text:  that.text,
            },
          },
        };




        this.ttsWS.send(JSON.stringify(params));
      }

      start(message) {
        total_res = ""; // 请空回答历史
        this.connectWebSocket(message);
      }

      // websocket接收数据的处理
      result(resultData) {
        let jsonData = JSON.parse(resultData);
        // console.log(jsonData);
        let  content =  jsonData.payload?.choices?.text[0].content
        console.log(jsonData.payload?.choices?.text[0].content);
        total_res +=  content ;
        // xfa-1: 注释
        // $("#output_text").val(total_res);
        // console.log(resultData)
        // 提问失败

        that.list[that.list.length -1].message +=  content
        that.scrollToBottom()
        if (jsonData.header.code !== 0) {
          that.btnIsDisabled()
          alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
          console.error(`${jsonData.header.code}:${jsonData.header.message}`);
          return;
        }
        if (jsonData.header.code === 0 && jsonData.header.status === 2) {
          // that.list.push({
          //   left: true,
          //   message: total_res 
          // })

          that.text.push({
            role: "system",
            content: this.message,
          })

          that.btnIsDisabled()
          this.ttsWS.close();
          bigModel.setStatus("init");
        }
      }
    }

    let  bigModel = new TTSRecorder();
    this.bigModel = bigModel
    // ======================开始调用=============================
    // var vConsole = new VConsole();
    this.bigModel.onWillStatusChange = function (oldStatus, status) {
      console.log(`output->oldStatus, status`, oldStatus, status);
    };
  },
  components: {
    VueMarkdown
  },
  methods:{
    formatCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const seconds = now.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    stopAnswer(){
      this.ttsWS.close()
      // 隐藏
      this.btnIsDisabled()
    }
  }

};
